import { createServer } from 'http';
const PORT = process.env.PORT;
const users = [
    { "id":1,"name": '张三' },
    { "id":2,"name": '李四' },
    { "id":3,"name": '王五' }
];

//logger 中间件
const logger = (req,res,  next )=>{
    console.log(`${req.method}${req.url}`);
    next();//调用下一个中间件
}
// JSON 中间件
const jsonMiddleware = (req, res, next) => {
    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    next();
};
//路由处理GET /api/users
const getUsersHandler = (req,res) =>{
    res.write(JSON.stringify(users));
    res.end();
};
//路由处理GET /api/users/：id
const getUserHandler = (req, res) => {
    const match = req.url.match(/^\/api\/users\/(\d+)/);
    if (match) {
        const id = parseInt(match[1], 10);
        const user = users.find(user => user.id === id);

        if (user) {
            res.write(JSON.stringify(user));
        } else {
            res.statusCode = 404;
            res.write(JSON.stringify({ message: '用户不存在' }));
        }
    } else {
        res.statusCode = 404;
        res.write(JSON.stringify({ message: '无效的用户 ID' }));
    }
    res.end();
};

//路由处理404
const notFoundHandler = (req,res) =>{
    res.statusCode = 404;
    res.write(JSON.stringify({message:'API不存在'}));
    res.end();
}

//路由处理 POST /api/users
const createUserHandler = (req,res) =>{
    let body ='';
    //监听'data'事件，逐块接收请求体的数据
    req.on('data',(chunk) =>{
        body +=chunk.toString();
    });
    //数据接收完毕后，触发'end'事件
    req.on('end',() =>{
        try {
        const user = JSON.parse(body);//解析请求体中的JSON数据
        users.push(user);//将解析出的用户添加到用户列表中
        res.statusCode =201;//设置响应状态码为201，表示创建成功
        res.write(JSON.stringify(user));//返回创建的用户数据
        res.end();
    } catch(error){
        console.error('解析JSON错误：',error);
        res.statusCode =400;
        res.write(JSON.stringify({message:'无效的JSON格式'}));
        res.end();
    }}
    );
    req.on('error', (error) => {
        console.error('请求处理错误:', error);
        res.statusCode = 500;
        res.write(JSON.stringify({ message: '内部服务器错误' }));
        res.end();
    });
};


const server = createServer((req,res) =>{

    logger(req,res,() =>{
        jsonMiddleware(req,res,() =>{
            if(req.url === '/api/users' &&req.method === 'GET'){
                getUsersHandler(req,res);
            }else if(req.url.match(/\/api\/users\/([0-9]+)/)&& req.method ==='GET'){
                getUserHandler(req,res);
            }else if(req.url ==='/api/users'&& req.method ==='POST'){
                createUserHandler(req,res);
            }else{
                notFoundHandler(req,res);
            }
        })
        
            
    }); 
})
server.listen(8000,() =>{
    console.log(`服务器已启用，监听端口${PORT}`);
});